package org.scohen.juploadr.util;

import java.text.DecimalFormat;

import org.scohen.juploadr.Messages;

/**
 * Utility classes for conversions
 * @author steve
 *
 */
public class ConversionUtils {
    private static final long ONE_MEG = 1024 * 1024;
    private static final DecimalFormat fmt = new DecimalFormat("###,###,###,##0.0"); //$NON-NLS-1$
    
    /**
     * Converts bytes to a more human readable format. 
     * 1024 bytes = 1 K 
     * 1024 K = one Meg
     * 1024 Megs = 1 Gigabye
     * @param bytes The number of bytes 
     * @return a String with a more human readable format
     */
    public static synchronized String bytesToHumanReadable(long bytes) {

        StringBuffer humanReadable = new StringBuffer();
        if (bytes < 1024) {
            humanReadable.append(fmt.format(bytes));
            humanReadable.append(Messages.getString("juploadr.ui.label.bytes")); //$NON-NLS-1$
        } else if (bytes < ONE_MEG) {
            humanReadable.append(fmt.format(bytes / 1024f));
            humanReadable.append(Messages.getString("juploadr.ui.label.kilobytes")); //$NON-NLS-1$
        } else if (bytes < 1024 * ONE_MEG) {
            humanReadable.append(fmt.format((float) bytes / (float) ONE_MEG));
            humanReadable.append(Messages.getString("juploadr.ui.label.megabytes")); //$NON-NLS-1$
        } else {
            humanReadable.append(fmt.format((float) bytes / (float) (ONE_MEG * 1024)));
            humanReadable.append(Messages.getString("juploadr.ui.label.gigabytes")); //$NON-NLS-1$
        }
        return humanReadable.toString();
    }
}
